<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2020/12/18
 * Time: 13:54
 */

namespace app\api\controller\v23;

use app\api\controller\v2\Auth;
use app\common\cachemodel\FortuneCache;
use app\common\cachemodel\MonthFortune;
use app\common\cachemodel\Recode as RecodeModel;
use app\common\cachemodel\YearFortune;
use app\common\cachemodel\ZlFortuneYearFeedback;
use app\common\lib\astrolog\FortunesChange;
use app\common\lib\Util;
use app\common\model\AppLogicVersion;
use app\common\model\Orders;
use app\common\model\SystemLogicVersion;
use think\Env;

/**
 * 年运
 * @desc 年运重点增加排序
 * @support 2.5.2
 * @doc [PRD文档](https://n6jotd4oi4.feishu.cn/docs/doccnTMvt3vMKt0sqLR7Hz265Sd)
 * @doc [蓝湖设计图](https://lanhuapp.com/web/#/item/project/board?pid=a901cc33-b4d6-4df5-9e3c-eee29012be95)
 * Class FortuneForYear
 * @package app\api\controller\v21
 */
class FortuneForYear extends Auth
{
    protected $year_id;
    protected $active_switch;

    protected $colors = [
        0 => ['name' => '困难', 'color' => '#7775ff',],
        1 => ['name' => '警戒', 'color' => '#ffa536',],
        2 => ['name' => '平平', 'color' => '#ffed17',],
        3 => ['name' => '吉利', 'color' => '#00f4e7',],
        4 => ['name' => '大吉', 'color' => '#00e9a0',],
    ];

    public function _initialize()
    {
        parent::_initialize();

        $this->year_id = config('goods.year_id');
        $this->active_switch = false;
    }

    /**
     * 查看年运
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作');
        }

        $uid = (int)$this->user['id'];
        $rid = input('param.rid/d', 0);
        $year = input('param.year/d', 0);
        // 当前查看的时间
        $now_time = strtotime($year . '-1');
        // 参数验证
        if (!$uid || !$rid || strlen($year) !== 4 || !$now_time)
        {
            return show(config('code.error'), '未知操作');
        }

        // 日历显示时间范围
        $fortune_time_range = config('fortune.fortune_time_range');
        $range_start = $fortune_time_range['year']['start'];
        $range_end = $fortune_time_range['year']['end'];
        // 解锁状态
        $unlock_status = 0;
        $OrdersModel = new Orders();
        $recode_info = (new RecodeModel())->getInfoById($rid);
        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        // 获取已解锁的时间范围
        $unlockYears = (new YearFortune())->getReocdeFortuneUnlockYears($rid);
        $unlockYears = array_map(function ($timeValue)
        {
            return (string)($timeValue);
        }, $unlockYears);
        // 更新逻辑数据定义
        $update_logic = [
            'title' => '',
            'content' => '',
            'status' => 0
        ];
        // 默认返回数据
        $fortune = [
            'fortune_year_change' => [],
            'fortune_year_stage' => [],
            'fortune_year_summarize' => [],
            'fortune_year_outline' => [],
        ];
        $fortune_score_list = [];
        $feedback = [];
        $unlockRecodeInfo = null;
        if (in_array($year, $unlockYears, false))
        {
            $fortuneDetail = (new FortunesChange())->init2($recode_info, $year, 'year', $this->headers['version']);
            $unlock_status = (int)$fortuneDetail['status'];
            // 用户计算成功后,获取年运信息及查询逻辑版本
            if ($unlock_status === 2)
            {
                $fortune = $fortuneDetail['fortune'];
                /**
                 * 1.7版本新增学业模块，低版本不返回该数据
                 * 否则安卓端不显示年运曲线
                 */
                $rec = Util::CheckAppVersion('1.7.0');
                if ($rec === '小')
                {
                    if (count($fortune['fortune_year_change']) > 4)
                    {
                        array_pop($fortune['fortune_year_change']);
                    }
                }
                // 获取当前最新版本逻辑信息
                $SystemLogicModel = new SystemLogicVersion();
                $logic_data = $SystemLogicModel->getVersion(['type' => 3]);
                // 获取当前档案逻辑版本号
                $AppLogicModel = new AppLogicVersion();
                $user_logic = $AppLogicModel->getVersion(['rid' => $rid, 'type' => 3, 'time' => date('Y', $now_time)]);

                if ($user_logic)
                {
                    // 若查看的时间版本号不是最新,提示更新
                    if ($logic_data['version'] && $user_logic < $logic_data['version'])
                    {
                        $update_logic = [
                            'title' => $logic_data['title'],
                            'content' => $logic_data['content'],
                            'status' => 1,
                        ];
                    }
                } elseif (!$user_logic)
                {
                    $update_logic = [
                        'title' => $logic_data['title'],
                        'content' => $logic_data['content'],
                        'status' => 1,
                    ];
                }

                //过滤检测返回的列表，是否超过当前的日期
                $sort_arry = [];//排序数据
                if (isset($fortune['fortune_year_stage']))
                {
                    $time_now = time();
                    $year_now = date('Y') * 1;
                    foreach ($fortune['fortune_year_stage'] as $k => $v)
                    {
                        if (isset($v['end_time']))
                        {
                            $arr_time_end = date_parse_from_format('Y.m.d', $year . '.' . $v['end_time']);
                            $time_end = mktime(23, 59, 59, $arr_time_end['month'], $arr_time_end['day'], $arr_time_end['year']);
                            $arr_time_start = date_parse_from_format('Y.m.d', $year . '.' . $v['start_time']);
                            $time_start = mktime(23, 59, 59, $arr_time_start['month'], $arr_time_start['day'], $arr_time_start['year']);
                            /**
                             * 问题【1.是否只有今年才排序，过去的几年或者未来的几年都不处理；【所有年份都需要进行排序，过去几年置灰 未来不置灰】
                             * 2.未过期/已过期的时间排序 是按照 单个标题开始时间排序还是结束时间排序；【没过期的已过期都按照开始时间排序】
                             * 3.老版本的得分不变，新版本及以后大于1.9.6版本的分值变化为0~100区间；【同意】
                             * 4.词条修改 建议老版本和新版本都变化，因为主要修改的是 词条语句不通【同意】
                             * 小于当前年，都过期
                             */
                            if ($year < $year_now)
                            {
                                $v['is_expired'] = 1;
                            } else if ($year === $year_now)
                            {//等于当前年

                                if ($time_now > $time_end)
                                {
                                    $v['is_expired'] = 1;
                                } else
                                {
                                    $v['is_expired'] = 0;
                                }

                            } else
                            {//大于当前年，没过期
                                $v['is_expired'] = 0;
                            }
                            //排序类型
                            $sort_arry['is_expired'][$k] = $v['is_expired'];
                            $v['start_timestamp'] = $time_start;

                            $sort_arry['start_timestamp'][$k] = $time_start;
                            $fortune['fortune_year_stage'][$k] = $v;
                        }
                    }

                    //排序
                    array_multisort($sort_arry['is_expired'], SORT_ASC, $sort_arry['start_timestamp'], SORT_ASC, $fortune['fortune_year_stage']);
                    //去掉 start_timestamp key
                    foreach ($fortune['fortune_year_stage'] as $k => $v)
                    {
                        if (isset($v['start_timestamp']))
                        {
                            unset($v['start_timestamp']);
                            $fortune['fortune_year_stage'][$k] = $v;
                        }
                    }
                }

                $fortune_score_list = [
                    [
                        'name' => '整体',
                        'color' => '#44D7B6',
                        'average_score' => 39,
                        'score_list' => [],
                    ],
                    [
                        'name' => '婚恋',
                        'color' => '#FF8FAC',
                        'average_score' => 19,
                        'score_list' => [],
                    ],
                    [
                        'name' => '财富',
                        'color' => '#FFEB40',
                        'average_score' => 78,
                        'score_list' => [],
                    ],
                    [
                        'name' => '事业',
                        'color' => '#9A9BFF',
                        'average_score' => 32,
                        'score_list' => [],
                    ]
                ];

                foreach ($fortune['fortune_year_change'] as $k1 => $v1)
                {
                    $totalScore = 0;
                    $totalNum = 0;
                    $maxItem = [];
                    $minItem = [];
                    $itemCount = count($v1);
                    foreach ($v1 as $k2 => $v2)
                    {
                        $totalNum++;
                        $totalScore += $v2['score'];
                        // 曲线图中的圆点样式【0=>默认无，1=>运势高点（绿色的），2=>运势低点（紫色的）】
                        $v1[$k2]['type'] = 0;

                        if ($k2 > 0 && $k2 < $itemCount - 1)
                        {
                            $preScore = $v1[$k2 - 1]['score'];
                            $nextScore = $v1[$k2 + 1]['score'];
                            // 暂存转折点的key
                            if ($v2['score'] > $preScore && $v2['score'] > $nextScore)
                            {
                                $maxItem[] = ['key' => $k2, 'score' => $v2['score']];
                            } elseif ($v2['score'] < $preScore && $v2['score'] < $nextScore)
                            {
                                $minItem[] = ['key' => $k2, 'score' => $v2['score']];
                            }
                        }
                    }
                    // 仅取3个最高点
                    if (count($maxItem) > 3)
                    {
                        $maxItem = resort($maxItem, 'score', 'DESC');
                    }
                    // 仅取3个最低点
                    if (count($minItem) > 3)
                    {
                        $minItem = resort($minItem, 'score', 'ASC');
                    }
                    // 取3个转折点
                    for ($i = 0; $i < 3; $i++)
                    {
                        if (isset($maxItem[$i]))
                        {
                            // 曲线图中的圆点样式【0=>默认无，1=>运势高点（绿色的），2=>运势低点（紫色的）】
                            $v1[$maxItem[$i]['key']]['type'] = 1;
                        }

                        if (isset($minItem[$i]))
                        {
                            // 曲线图中的圆点样式【0=>默认无，1=>运势高点（绿色的），2=>运势低点（紫色的）】
                            $v1[$minItem[$i]['key']]['type'] = 2;
                        }
                    }
                    $averageScore = ceil($totalScore / $totalNum);
                    if ($k1 === 4)
                    {
                        $fortune_score_list[$k1] = [
                            'name' => '学业',
                            'color' => '#3485FF',
                            'average_score' => $averageScore,
                            'score_list' => $v1,
                        ];
                    } else
                    {
                        // 取平均分，向上取整
                        $fortune_score_list[$k1]['average_score'] = $averageScore;

                        $fortune_score_list[$k1]['score_list'] = $v1;
                    }

                    $scorePercent = Util::getScorePercentInfo($averageScore);
                    $fortune_score_list[$k1]['percent1'] = $scorePercent['percent'];
                    $fortune_score_list[$k1]['color1'] = $scorePercent['color'];
                }

                $feedback = (new ZlFortuneYearFeedback())->getFortuneYearFeedbackInfo($rid, $year);

                $unlockRecodeInfo = [
                    'recode_is_change' => $fortuneDetail['recode_is_change'],
                    'info' => (new Util)->getFortuneDetailRecodeInfo([$fortuneDetail['recode_info']], (int)$this->user['rid']),
                    'change_title' => $fortuneDetail['recode_is_change'] ? '检测到档案信息发生修改' : '',
                    'change_desc' => $fortuneDetail['recode_is_change'] ? '已购买的运势内容不会随着档案的修改重新计算' : ''
                ];
            }
        }

        // 统计订单人数
        $fortune_base_num = $OrdersModel->fortune_base(['type' => 2]);

        if ($unlock_status == 0)
        {
            $unlock_tips = [
                'title' => '年度报告解锁',
                'content' => '解锁当前运势，可查看你的' . $year . '年会发生什么，哪方面是今年的重点，它们是吉是凶，一整年又会有哪些起伏变化。（注意：解锁年运不包含月运）
一眼看穿365天，提前预知,早做安排。'
            ];
        } elseif ($unlock_status == 1)
        {
            $unlock_tips = [
                'title' => '年度报告计算等待中...',
                'content' => '由于年运的计算量较大,准了将在24小时内为您献上您所需要的年运。
小伙伴们耐心等待哦~',
            ];
        } else
        {
            $unlock_tips = null;
        }


        $data = [
            'time' => $unlockYears,
            'fortune_year_summarize' => $fortune['fortune_year_summarize'],
            'fortune_year_outline' => $fortune['fortune_year_outline'],
            'fortune_score_list' => $fortune_score_list,
            'fortune_year_stage' => $fortune['fortune_year_stage'],
            'unlock_num' => (int)($fortune_base_num),
            'unlock_status' => $unlock_status,
            'time_range' => [
                'start_time' => $range_start,
                'end_time' => $range_end,
            ],
            'update_logic' => $update_logic,
            'unlock_tips' => $unlock_tips,
            'unlock_recode_info' => $unlockRecodeInfo
        ];

        // 活动开关，默认关闭
        $config = config('active.fortune_active');

        $host = Env::get('host.domain');

        $data['active_switch'] = [
            'day_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => '',
                'target' => 'link',
                'link' => $host . '/web/fortune_year/active_details',//大礼包h5
            ],
            'month_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => $host . '/web/fortune_year/active_details',//大礼包h5
            ],
            'year_active' => [
                'is_open' => false,
                'icon' => $config['icon'],
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => $host . '/web/fortune_year/active_details',//大礼包h5
            ]
        ];

        // 若未解锁并在活动时间内，开启
        if ($this->active_switch)
        {
            $data['active_switch']['day_active']['is_open'] = false;
            $data['active_switch']['month_active']['is_open'] = true;
            $data['active_switch']['year_active']['is_open'] = true;
        }

        /**
         * 年运 意见反馈
         * 仅在已解锁时返回该数据
         */
        $data['feedback'] = $feedback;

        $data['luck_adversity'] = $this->colors;

        return show(config('code.success'), '加载成功', $data);
    }
}
